﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Threading;
using NekoVampire.TwitterClient.Controls;
using NekoVampire.TwitterClient.Twitter;
using NekoVampire.Extension;

namespace NekoVampire.TwitterClient.Forms
{
    public partial class User : Form
    {
        AccessTwitter Twitter;
        Storage storage;
        public string UserName;
        private List<Status> TimeLine;
        private Thread thread;

        public User(AccessTwitter Twitter,Storage storage)
        {
            thread = new Thread(new ThreadStart(ShowThread));
            thread.IsBackground = true;

            this.Twitter = Twitter;
            this.storage = storage;
            InitializeComponent();
        }

        public void Show(string user)
        {
            this.UserName = user;
            base.Show();

            this.Text = UserName;
            thread.Start();
        }

        public void ShowDialog(string user)
        {
            this.UserName = user;
            base.ShowDialog();

            this.Text = UserName;
            thread.Start();
        }


        private void ShowThread()
        {
            XElement user;
            try
            {
                user = XElement.Load(XmlReader.Create(Twitter.ShowUser(this.UserName)));
            }
            catch (WebException ex)
            {
                if (!IsHandleCreated)
                    return;
                Invoke((MethodInvoker)delegate
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = ex.Message;
                    listView1.Items.Add(item);
                });
                return;
            }

            if (!IsHandleCreated)
                return;

            XElement error;
            if((error = user.Element("error")) != null)
            {
                Invoke((MethodInvoker)delegate
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = error.Value;
                    listView1.Items.Add(item);
                });
            }

            bool protect = bool.Parse(user.Element("protected").Value);
            Invoke((MethodInvoker)delegate
            {
                this.userNameLabel.Text = user.Element("name").Value;
                this.screenNameLabel.Text = user.Element("screen_name").Value;
                this.locationLabel.Text = user.Element("location").Value;
                this.descriptionLabel.Text = user.Element("description").Value;
                this.pictureBox1.Image = storage.GetImage(user.Element("profile_image_url").Value).GetResizedImage(64, 64, true);
                this.Text = "@" + this.screenNameLabel.Text + "/" + this.userNameLabel.Text;
                if(protect)
                    this.userNameLabel.Text = "[protected]" + this.userNameLabel.Text;
            });
            if(protect)
            {
                Invoke((MethodInvoker)delegate
                {
                    this.userNameLabel.ForeColor = Color.Red;

                    ListViewItem item = new ListViewItem();
                    item.Text = "このユーザーのつぶやきは非公開です。";
                    listView1.Items.Add(item);
                });
            }

            XElement timeLine = null;

            try
            {
                timeLine = XElement.Load(XmlReader.Create(Twitter.GetUserTimeLine(this.UserName)));
            }
            catch (WebException ex)
            {
                if (!IsHandleCreated)
                    return;
                Invoke((MethodInvoker)delegate
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = ex.Message;
                    listView1.Items.Add(item);
                });
                return;
            }

            if (!IsHandleCreated)
                return;
            if ((error = timeLine.Element("error")) != null)
            {
                ListViewItem item = new ListViewItem();
                item.Text = error.Value;
                listView1.Items.Add(item);
            }

            TimeLine = new List<Status>();
            foreach (XElement status in timeLine.Elements("status"))
            {
                Status stat = new Status(status);
                TimeLine.Add(stat);
            }
            Invoke((MethodInvoker)delegate { timeLineViewAdding(); });

            try
            {
                timeLine = XElement.Load(XmlReader.Create(Twitter.ExistFriend(this.UserName)));
            }
            catch (WebException ex)
            {
                if (!IsHandleCreated)
                    return;
                Invoke((MethodInvoker)delegate
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = ex.Message;
                    listView1.Items.Add(item);
                });
                return;
            }
            Invoke((MethodInvoker)delegate
            {
                this.button1.Enabled = true;
                if (bool.Parse(timeLine.Value))
                    this.button1.Text = "フォロー中";
                else
                    this.button1.Text = "フォローする";
            });
        }

        public void timeLineViewAdding()
        {
            listView1.Items.Clear();

            foreach (Status status in TimeLine)
            {
                ListViewItemEx item = new ListViewItemEx();
                item.Tag = status;
                item.Text = status.text;
                item.SubItems.Add(status.createdAt.ToString());
                listView1.Items.Add(item);
            }
        }

        private void User_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread.IsAlive)
            {
                thread.Abort();
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://twitter.com/" + this.UserName);
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            twitterStatusView1.Status = ((ListViewItemEx)((ListView)sender).FocusedItem).Tag;
            twitterStatusView1.Image = storage.GetImage(twitterStatusView1.Status.user.profileImageUrl);
        }
    }
}
